package com.hhkj.api.common.common.component.manager;

import cn.hutool.core.util.RandomUtil;
import com.hhkj.api.common.common.cont.SaleCaptchaConst;
import com.hhkj.api.common.common.utils.SaleCaptchaUtils;
import com.hhkj.api.common.model.extend.SaleCaptcha;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.GlobalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * SaleCaptchaManager
 *
 * @author HHKJ-SERVER-ZJ
 * @since 2023/10/25 11:09
 */
@Component
public class SaleCaptchaManager {


    @Autowired
    private RedisCache redisCache;

    /**
     * 创建验证码并缓存
     *
     * @param typeCode 类型
     * @param mobile   手机号
     * @return 验证码信息
     */
    public SaleCaptcha createCaptcha(String typeCode, String mobile) {
        String cacheKey = SaleCaptchaUtils.createCacheKey(typeCode, mobile);
        String captcha = RandomUtil.randomNumbers(SaleCaptchaConst.CAPTCHA_LENGTH);
        SaleCaptcha saleCaptcha = new SaleCaptcha(typeCode, mobile, captcha, new Date());
        redisCache.setCacheObject(cacheKey, saleCaptcha, SaleCaptchaConst.CACHE_EFFECTIVE_DURATION_SECOND, TimeUnit.SECONDS);
        return saleCaptcha;
    }


    /**
     * 获取验证码信息
     *
     * @param typeCode 验证码类型
     * @param mobile   手机号
     * @return 验证码信息
     */
    public SaleCaptcha getCaptcha(String typeCode, String mobile) {
        String cacheKey = SaleCaptchaUtils.createCacheKey(typeCode, mobile);
        Object object = redisCache.getCacheObject(cacheKey);
        if (object == null) {
            return null;
        }
        if (!(object instanceof SaleCaptcha)) {
            throw new GlobalException("验证码读取失败，请联系管理员");
        }
        return (SaleCaptcha) object;
    }

}
